# Dreams have to come true after all
from datetime import datetime, timedelta

import jwt
from flask import current_app
from jwt import PyJWTError

from comment.models.User import User
from comment.utils import const


def generate_tokens(uid):
    """
    根据已经登录之后的用户ID,生成token
    :param uid:
    :return:
    """
    payload = {
        'id': uid,
        # exp代表token有效时间,且必须是标准时间
        'exp': datetime.utcnow() + timedelta(seconds=const.JWT_EXPIRY_SECOND)
    }
    s = jwt.encode(payload=payload, key=const.SECRET_KEY, algorithm='HS256')
    # 生成token
    return s


def verify_tokens(tokens_str):
    """
    验证token,并且验证成功后返回用户ID
    :param tokens_str:
    :return:
    """
    try:
        # 本质是一个解密过程
        data = jwt.decode(tokens_str, key=const.SECRET_KEY, algorithms='HS256')
        current_app.logger.info(data)
    except PyJWTError as e:
        current_app.logger.info(e)
        return {'message': 'token验证失败'}
    # token验证成功,查看用户状态
    user = User.query.filter(User.id == data['id']).first()
    if user and user.onlock != 0:
        return {'message': '数据表中用户过期'}
    return {'message': 'ok', 'id': user.id}
